package com.vanrin.aweatherforecast.view;

import com.vanrin.aweatherforecast.R;
import com.vanrin.aweatherforecast.XLog;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class FirstAnimationView extends View {

    Animation mCurrentAnimation = null;
    Transformation mTransformation = new Transformation();
    Bitmap bitmap = null;

    public FirstAnimationView(Context context, AttributeSet attrs) {
        super(context, attrs);
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.night_bg);
    }

    public void startAnimation(Animation animation) {
        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
        setAnimation(animation);
        invalidate();
    }

    protected void onDraw(Canvas canvas) {
        XLog.log("draw start...");
        long curTime = SystemClock.uptimeMillis();
        if (mCurrentAnimation == null) {
            canvas.drawBitmap(bitmap, 0, 0, null);
        } else {
            if (!mCurrentAnimation.isInitialized()) // initialize animation
                mCurrentAnimation.initialize(bitmap.getWidth(), bitmap.getHeight(), 300, 300);
            boolean more = mCurrentAnimation.getTransformation(curTime, mTransformation);
            if (more) {
                Matrix m = canvas.getMatrix();
                canvas.setMatrix(mTransformation.getMatrix());
                canvas.drawBitmap(bitmap, 0, 0, null);
                canvas.setMatrix(m);
                this.invalidate();
            } else {
                mCurrentAnimation = null;
                this.invalidate();
            }
        }
        XLog.log("draw end!");
    }
}
